package com.ailanyin.modules.generator.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ailanyin.common.base.constants.CommonConstant;
import com.ailanyin.common.base.exception.Assert;
import com.ailanyin.common.security.utils.SecurityUtil;
import com.ailanyin.modules.generator.constants.GenConstant;
import com.ailanyin.modules.generator.domain.GenTable;
import com.ailanyin.modules.generator.domain.GenTableColumn;
import com.ailanyin.modules.generator.mapper.GenTableColumnMapper;
import com.ailanyin.modules.generator.mapper.GenTableMapper;
import com.ailanyin.modules.generator.service.IGenTableService;
import com.ailanyin.modules.generator.utils.GenUtil;
import com.ailanyin.modules.generator.utils.VelocityInitializer;
import com.ailanyin.modules.generator.utils.VelocityUtil;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2022/9/26 0026 上午 11:34
 */
@Service
public class GenTableServiceImpl implements IGenTableService {

    private static final String ROOT_FILE_PATH = "/";
    @Resource
    private GenTableMapper genTableMapper;
    @Resource
    private GenTableColumnMapper genTableColumnMapper;

    @Override
    public List<GenTable> selectGenTableList(GenTable genTable) {
        return genTableMapper.selectGenTableList(genTable);
    }

    @Override
    public List<GenTable> selectDbTableList(GenTable genTable) {
        return genTableMapper.selectDbTableList(genTable);
    }

    @Override
    public List<GenTable> selectDbTableListByNames(String[] tableNames) {
        return genTableMapper.selectDbTableListByNames(tableNames);
    }

    @Override
    public List<GenTable> selectGenTableAll() {
        return genTableMapper.selectGenTableAll();
    }

    @Override
    public GenTable selectGenTableById(Long id) {
        GenTable genTable = genTableMapper.selectGenTableById(id);
        setTableFromOptions(genTable);
        return genTable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGenTable(GenTable genTable) {
        String options = JSONUtil.toJsonStr(genTable.getParams());
        genTable.setOptions(options);
        int row = genTableMapper.updateGenTable(genTable);
        if (row > 0) {
            for (GenTableColumn cenTableColumn : genTable.getColumns()) {
                genTableColumnMapper.updateGenTableColumn(cenTableColumn);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteGenTableByIds(Long[] tableIds) {
        genTableMapper.deleteGenTableByIds(tableIds);
        genTableColumnMapper.deleteGenTableColumnByIds(tableIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importGenTable(List<GenTable> tableList) {
        String username = SecurityUtil.getLoginUsername();
        try {
            for (GenTable table : tableList) {
                String tableName = table.getTableName();
                GenUtil.initTable(table, username, "com.ailanyin.modules.generator" , "ailanyin");
                int row = genTableMapper.insertGenTable(table);
                if (row > 0) {
                    // 保存列信息
                    List<GenTableColumn> genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
                    for (GenTableColumn column : genTableColumns) {
                        GenUtil.initColumnField(column, table);
                        genTableColumnMapper.insertGenTableColumn(column);
                    }
                }
            }
        } catch (Exception e) {
            Assert.fail("导入失败：" + e.getMessage());
        }
    }

    @Override
    public Map<String, String> previewCode(Long tableId) {
        Map<String, String> dataMap = new LinkedHashMap<>();
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableById(tableId);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);
        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtil.prepareContext(table);

        // 获取模板列表
        List<String> templates = VelocityUtil.getTemplateList(table.getTplCategory());
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, CommonConstant.UTF8);
            tpl.merge(context, sw);
            dataMap.put(template, sw.toString());
        }
        return dataMap;
    }

    @Override
    public byte[] downloadCode(String tableName) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        generatorCode(tableName, zip);
        IoUtil.close(zip);
        return outputStream.toByteArray();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncDb(String tableName) {
        GenTable table = genTableMapper.selectGenTableByName(tableName);
        List<GenTableColumn> tableColumns = table.getColumns();
        Map<String, GenTableColumn> tableColumnMap = tableColumns.stream().collect(Collectors.toMap(GenTableColumn::getColumnName, Function.identity()));

        List<GenTableColumn> dbTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
        if (CollectionUtil.isEmpty(dbTableColumns)) {
            Assert.fail("同步数据失败，原表结构不存在");
        }
        List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());

        dbTableColumns.forEach(column -> {
            GenUtil.initColumnField(column, table);
            if (tableColumnMap.containsKey(column.getColumnName())) {
                GenTableColumn prevColumn = tableColumnMap.get(column.getColumnName());
                column.setColumnId(prevColumn.getColumnId());
                if (column.isList()) {
                    // 如果是列表，继续保留查询方式/字典类型选项
                    column.setDictType(prevColumn.getDictType());
                    column.setQueryType(prevColumn.getQueryType());
                }
                // 如果是(新增/修改&非主键/非忽略及父属性)，继续保留必填/显示类型选项
                if (StrUtil.isNotEmpty(prevColumn.getIsRequired()) && !column.isPk()) {
                    if (column.isInsert() || column.isEdit()) {
                        if (column.isUsableColumn() || !column.isSuperColumn()) {
                            column.setIsRequired(prevColumn.getIsRequired());
                            column.setHtmlType(prevColumn.getHtmlType());
                        }

                    }
                }
                genTableColumnMapper.updateGenTableColumn(column);
            } else {
                genTableColumnMapper.insertGenTableColumn(column);
            }
        });

        List<GenTableColumn> delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(delColumns)) {
            genTableColumnMapper.deleteGenTableColumns(delColumns);
        }
    }

    @Override
    public byte[] downloadCode(String[] tableNames) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames) {
            generatorCode(tableName, zip);
        }
        IoUtil.close(zip);
        return outputStream.toByteArray();
    }

    @Override
    public void validateEdit(GenTable genTable) {
        if (GenConstant.TPL_TREE.equals(genTable.getTplCategory())) {
            String options = JSONUtil.toJsonStr(genTable.getParams());
            JSONObject paramsObj = JSONUtil.parseObj(options);
            if (StrUtil.isEmpty(paramsObj.getStr(GenConstant.TREE_CODE))) {
                Assert.fail("树编码字段不能为空");
            } else if (StrUtil.isEmpty(paramsObj.getStr(GenConstant.TREE_PARENT_CODE))) {
                Assert.fail("树父编码字段不能为空");
            } else if (StrUtil.isEmpty(paramsObj.getStr(GenConstant.TREE_NAME))) {
                Assert.fail("树名称字段不能为空");
            } else if (GenConstant.TPL_SUB.equals(genTable.getTplCategory())) {
                if (StrUtil.isEmpty(genTable.getSubTableName())) {
                    Assert.fail("关联子表的表名不能为空");
                } else if (StrUtil.isEmpty(genTable.getSubTableFkName())) {
                    Assert.fail("子表关联的外键名不能为空");
                }
            }
        }
    }

    @Override
    public void generatorCode(String tableName) {
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableByName(tableName);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);

        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtil.prepareContext(table);

        // 获取模板列表
        List<String> templates = VelocityUtil.getTemplateList(table.getTplCategory());
        for (String template : templates) {
            if (!StrUtil.containsAny(template, "sql.vm" , "api.js.vm" , "index.vue.vm" , "index-tree.vue.vm")) {
                // 渲染模板
                StringWriter sw = new StringWriter();
                Template tpl = Velocity.getTemplate(template, CommonConstant.UTF8);
                tpl.merge(context, sw);
                try {
                    String path = getGenPath(table, template);
                    FileUtil.writeString(sw.toString(), new File(path), Charset.forName(CommonConstant.UTF8));
                } catch (Exception e) {
                    Assert.fail("渲染模板失败，表名：" + table.getTableName());
                }
            }
        }
    }

    /**
     * 查询表信息并生成代码
     */
    private void generatorCode(String tableName, ZipOutputStream zip) {
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableByName(tableName);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);

        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtil.prepareContext(table);

        // 获取模板列表
        List<String> templates = VelocityUtil.getTemplateList(table.getTplCategory());
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, CommonConstant.UTF8);
            tpl.merge(context, sw);
            try {
                // 添加到zip
                zip.putNextEntry(new ZipEntry(VelocityUtil.getFileName(template, table)));
                IoUtil.write(zip, false, sw.toString().getBytes());
                IoUtil.close(sw);
                zip.flush();
                zip.closeEntry();
            } catch (IOException e) {
                Assert.fail("渲染模板失败，表名：" + table.getTableName() + e);
            }
        }
    }

    /**
     * 设置主子表信息
     *
     * @param table 业务表信息
     */
    private void setSubTable(GenTable table) {
        String subTableName = table.getSubTableName();
        if (StrUtil.isNotBlank(subTableName)) {
            table.setSubTable(genTableMapper.selectGenTableByName(subTableName));
        }
    }

    /**
     * 设置主键列信息
     *
     * @param table 业务表信息
     */
    private void setPkColumn(GenTable table) {
        for (GenTableColumn column : table.getColumns()) {
            if (column.isPk()) {
                table.setPkColumn(column);
                break;
            }
        }
        if (ObjectUtil.isNull(table.getPkColumn())) {
            table.setPkColumn(table.getColumns().get(0));
        }
        if (GenConstant.TPL_SUB.equals(table.getTplCategory())) {
            for (GenTableColumn column : table.getSubTable().getColumns()) {
                if (column.isPk()) {
                    table.getSubTable().setPkColumn(column);
                    break;
                }
            }
            if (ObjectUtil.isNull(table.getSubTable().getPkColumn())) {
                table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0));
            }
        }
    }

    /**
     * 获取代码生成地址
     *
     * @param table    业务表信息
     * @param template 模板文件路径
     * @return 生成地址
     */
    private static String getGenPath(GenTable table, String template) {
        String genPath = table.getGenPath();
        if (StrUtil.equals(genPath, ROOT_FILE_PATH)) {
            return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtil.getFileName(template, table);
        }
        return genPath + File.separator + VelocityUtil.getFileName(template, table);
    }

    /**
     * 设置代码生成其他选项值
     *
     * @param genTable 设置后的生成对象
     */
    private void setTableFromOptions(GenTable genTable) {
        JSONObject paramsObj = JSONUtil.parseObj(genTable.getOptions());
        if (ObjectUtil.isNotNull(paramsObj)) {
            String treeCode = paramsObj.getStr(GenConstant.TREE_CODE);
            String treeParentCode = paramsObj.getStr(GenConstant.TREE_PARENT_CODE);
            String treeName = paramsObj.getStr(GenConstant.TREE_NAME);
            String parentMenuId = paramsObj.getStr(GenConstant.PARENT_MENU_ID);
            String parentMenuName = paramsObj.getStr(GenConstant.PARENT_MENU_NAME);

            genTable.setTreeCode(treeCode);
            genTable.setTreeParentCode(treeParentCode);
            genTable.setTreeName(treeName);
            genTable.setParentMenuId(parentMenuId);
            genTable.setParentMenuName(parentMenuName);
        }
    }
}
